﻿'Description:自动开卡业务类
'Copyright (c) : 通力凯顿（北京）系统集成有限公司
'Writer:zhangrj
'create Date:2023-12-22
'Rewriter:
'Rewrite Date:
Imports BusinessRule.DTO
Imports BusinessRule.IBusiness
Imports DatabaseAccess.DBUtility
Imports Camstar.WebClient.WebServicesProxy.InSiteWebServices
Imports System.Data
Imports System.Text
Imports External.APICalling
Imports System.Data.OracleClient
Imports BusinessRule.Common

Public Class AutoStartContainerBusiness

    Private commonBusiness As New uLMSCommonBusiness
    Private containerBusiness As New uLMSContainerBusiness
    Private sendToWms As New uLMSSendDataToWmsBusiness

    ''' <summary>
    ''' 获取待开卡的订单
    ''' </summary>
    ''' <param name="dic"></param>
    ''' <param name="isPage"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function GetNotStartContainerOrderInfo(ByVal dic As Dictionary(Of String, String), ByVal isPage As Boolean) As uMESProcessResult
        Dim result As New uMESProcessResult
        Try
            Dim sql As StringBuilder = New StringBuilder()
            sql.AppendLine(<string>SELECT Distinct m.mfgorderid,m.mfgordername,pb.productname,ua.attributevalue mrpcontrol,m.qty,
                        m.plannedstartdate, m.plannedcompletiondate, m.productfamilyname, u.uomname,f.factoryname,wct.workcentername,te.teamname
                        FROM mfgorder m
                        LEFT JOIN ORDERSTATUS os ON os.orderstatusid = m.orderstatusid
                        LEFT JOIN USERATTRIBUTE UA ON UA.PARENTID = m.MFGORDERID AND UA.USERATTRIBUTENAME = 'MRP控制者'
                        LEFT JOIN PRODUCTBASE pb1  ON pb1.PRODUCTBASEID = m.PRODUCTBASEID
                        LEFT JOIN PRODUCT P ON P.PRODUCTID = NVL(pb1.REVOFRCDID, m.PRODUCTID)
                        LEFT JOIN PRODUCTBASE PB ON PB.PRODUCTBASEID = P.PRODUCTBASEID
                        LEFT JOIN WORKFLOWBASE WB1 ON WB1.WORKFLOWBASEID = P.WORKFLOWBASEID
                        LEFT JOIN WORKFLOW W ON W.WORKFLOWID =NVL(WB1.REVOFRCDID,  P.WORKFLOWID)
                        LEFT JOIN WORKFLOWBASE WB ON WB.WORKFLOWBASEID = W.WORKFLOWBASEID
                        LEFT JOIN uom u ON u.uomid = m.uomid
                        INNER JOIN containerAutoStartRule ca ON ca.productname = pb.productname AND ca.status = 1
                        
                        LEFT JOIN productteaminfo pti ON pti.productname = pb.productname AND pti.isuse = 0
                        LEFT JOIN team te ON te.teamid = pti.teamid
                        LEFT JOIN workcenter wct ON wct.workcenterid = te.workcenterid
                        LEFT JOIN factory f ON f.factoryid = wct.factoryid

                        WHERE NOT EXISTS (SELECT 1 FROM container c WHERE c.mfgorderid = m.mfgorderid AND c.status != 0)
                        AND m.QTY > 0 AND NVL(os.orderstatusname,'打开') = '打开' AND NVL(m.sendstart,'0') = '1'</string>.Value)

            sql.AppendFormat(" AND m.factoryid = '{0}'", dic("FactoryID"))

            If dic.ContainsKey("OrderName") Then
                If Not String.IsNullOrWhiteSpace(dic("OrderName")) Then
                    sql.AppendFormat(" AND m.mfgordername = '{0}'", dic("OrderName"))
                End If
            End If

            If dic.ContainsKey("ProductName") Then
                If Not String.IsNullOrWhiteSpace(dic("ProductName")) Then
                    sql.AppendFormat(" AND pb.productname = '{0}'", dic("ProductName"))
                End If
            End If

            '分厂
            If dic.ContainsKey("factoryid") Then
                If Not String.IsNullOrWhiteSpace(dic("factoryid")) Then
                    sql.AppendFormat(" AND f.factoryid = '{0}'", dic("factoryid"))
                End If
            End If

            '工区
            If dic.ContainsKey("workcenterid") Then
                If Not String.IsNullOrWhiteSpace(dic("workcenterid")) Then
                    sql.AppendFormat(" AND wct.workcenterid = '{0}'", dic("workcenterid"))
                End If
            End If

            '单元
            If dic.ContainsKey("teamid") Then
                If Not String.IsNullOrWhiteSpace(dic("teamid")) Then
                    sql.AppendFormat(" AND te.teamid = '{0}'", dic("teamid"))
                End If
            End If

            sql.AppendLine(" ORDER BY pb.productname, m.plannedcompletiondate ASC")

            If isPage Then '如果分页
                Dim pageDto As uMESPagingDataDTO = New uMESPagingDataDTO()
                pageDto.CurrentPageIndex = Integer.Parse(dic("PageIndex").ToString())
                pageDto.PageSize = Integer.Parse(dic("PageSize").ToString())
                pageDto.strSQL = sql.ToString()
                result = DatabaseHelper.RunProcedureForPage(pageDto)
            Else
                result.DBTable = DatabaseHelper.Query_ReturnDatTable(sql.ToString)
                result.Result = True
            End If
        Catch ex As Exception
            result.Result = False
            result.Message = ex.Message
        End Try
        Return result
    End Function

    ''' <summary>
    ''' 一键开卡
    ''' </summary>
    ''' <param name="param"></param>
    ''' <param name="m_UserInfo"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function OneKeyStartContainerInfo(ByVal param As AutoStartContainerParam, ByVal m_UserInfo As CurrentUserInfo) As uMESProcessResult
        Dim result As uMESProcessResult = New uMESProcessResult()
        Try
            Dim res As Tuple(Of Boolean, String) = ValidAutoStartData(param)

            If Not res.Item1 Then
                result.Result = False
                result.Message = res.Item2
                result.ReturnData = "1" '表示不用插入错误日志
                Return result
                Exit Function
            End If

            Dim dtRule As DataTable = GetContainerStartRuleInfo(param.ProductName) '获取件号开卡规则
            If dtRule.Rows.Count = 0 Then
                result.Result = False
                result.Message = String.Format("件号：{0}未找到有效的开卡规则", param.ProductName)
                Return result
                Exit Function
            End If

            Dim drRule As DataRow = dtRule.Rows(0) '获取第一条数据，有效的开卡规则永远只有一条

            If String.IsNullOrWhiteSpace(drRule("workflowname").ToString()) Then
                result.Result = False
                result.Message = String.Format("件号：{0}，版本：{1}；未找到工艺规程", param.ProductName, drRule("productrevision").ToString())
                Return result
                Exit Function
            End If

            Dim dtWorkflowStep As DataTable = commonBusiness.GetWorkFlowSetps(New RevisionedObjectRef() With {
                .__name = drRule("workflowname").ToString(),
                .__rev = drRule("workflowrevision").ToString()
            })

            If dtWorkflowStep.Rows.Count = 0 Then
                result.Result = False
                result.Message = String.Format("件号：{0}，版本：{1}；工艺：{2}，版本：{3}；未找到工序信息", param.ProductName, drRule("productrevision").ToString(), drRule("workflowname").ToString(), drRule("workflowrevision").ToString())
                Return result
                Exit Function
            End If

            Dim cutQty = 0 '分卡数
            Dim cutStepName = String.Empty '分卡工序
            If drRule("iscutcontainer").ToString = "1" Then '如果规则设置了切断件，则验证
                If String.IsNullOrWhiteSpace(drRule("cutqty").ToString) Then
                    result.Result = False
                    result.Message = String.Format("件号：{0}开卡规则设置了切断件，但未填写分卡数", param.ProductName)
                    Return result
                    Exit Function
                End If
                If String.IsNullOrWhiteSpace(drRule("cutstartstep").ToString) Then
                    result.Result = False
                    result.Message = String.Format("件号：{0}开卡规则设置了切断件，但未填写分卡工序", param.ProductName)
                    Return result
                    Exit Function
                End If

                If dtWorkflowStep.Select(String.Format("WORKFLOWSTEPNAME = '{0}'", drRule("cutstartstep").ToString)).Length = 0 Then
                    result.Result = False
                    result.Message = String.Format("件号：{0}，版本：{1}；工艺：{2}，版本：{3}；对应工序列表中未找到分卡工序：{4}", param.ProductName, drRule("productrevision").ToString(), drRule("workflowname").ToString(), drRule("workflowrevision").ToString(), drRule("cutstartstep").ToString)
                    Return result
                    Exit Function
                End If
                cutQty = Integer.Parse(drRule("cutqty").ToString)
                cutStepName = drRule("cutstartstep").ToString

                '验证主卡加分卡数不等于订单数，则不可开卡（例：A件号订单数量为10，分卡数量维护为4（1件切断件还需切4件出来，总数为5件），那么主批次数量则等于（订单数/(分卡数量+1），那么这个订单开出来的批次号为A/2024001、A/2024001-1、A/2024001-2、A/2024001-3、A/2024001-4、A/2024002、A/2024002-1、A/2024002-2、A/2024002-3、A/2024002-4；主卡+分卡的总批次数量与订单数量一致（10）
                If (param.Qty Mod (cutQty + 1)) <> 0 Then
                    result.Result = False
                    result.Message = String.Format("件号：{0}，的开卡规则分卡数（{1}） + 主卡数与订单数（{2}）不一致", param.ProductName, cutQty, param.Qty)
                    Return result
                    Exit Function
                End If
                param.Qty = (param.Qty / (cutQty + 1)) '修改开卡数据
            End If

            Dim containerBaseInfo As ContainerStartInfo = New ContainerStartInfo()
            containerBaseInfo.ContainerName = GetContainerName(param.ProductName)
            containerBaseInfo.TogetherFlag = containerBaseInfo.ContainerName
            containerBaseInfo.ChildList = Nothing
            FillContainerProductFamily(containerBaseInfo, param.ProductFamilyName) '重组订单的机型并填充到批次上
            containerBaseInfo.MfgOrder = param.MfgOrderName
            containerBaseInfo.Qty = param.Qty
            containerBaseInfo.IsSelfMfg = drRule("isselfmfg").ToString()
            containerBaseInfo.Factory = m_UserInfo.Factory
            containerBaseInfo.CheckTechnique = drRule("technologyNum").ToString() '取技术员员工号
            containerBaseInfo.UOM = param.UomName
            containerBaseInfo.WorkCenter = drRule("workcentername").ToString()
            containerBaseInfo.Team = ""
            containerBaseInfo.StartEmployee = m_UserInfo.EmployeeName
            containerBaseInfo.Comment = ""
            containerBaseInfo.PlannedStartDate = DateTime.Parse(param.PlannedStartDate.ToString).ToString("yyyy-MM-ddTHH:mm:ss")
            containerBaseInfo.PlannedCompletionDate = DateTime.Parse(param.PlannedCompletionDate.ToString).ToString("yyyy-MM-ddTHH:mm:ss")
            containerBaseInfo.ContainerType = drRule("containertype").ToString()
            containerBaseInfo.QualificationQty = "1"
            FillContainerDefaultInfo(containerBaseInfo, m_UserInfo.FactoryID)
            containerBaseInfo.BeginStep = dtWorkflowStep.Rows(0)("WORKFLOWSTEPNAME").ToString()
            containerBaseInfo.MfgWorkflowName = drRule("workflowname").ToString()
            containerBaseInfo.MfgWorkflowRevision = drRule("workflowrevision").ToString()
            containerBaseInfo.MfgWorkflowuseROR = False
            containerBaseInfo.ProductName = param.ProductName
            containerBaseInfo.ProductRevision = drRule("productrevision").ToString()
            containerBaseInfo.ProductuseROR = False

            '通过批次类型开出不同类型的卡（7：单件单卡，2：批量加工，3：批量带子序号（暂定未做））
            Select Case drRule("containertype").ToString()
                Case "7"
                    Dim containerName As String = containerBaseInfo.ContainerName.ToString()
                    Dim message As String = String.Format("批次：{0},尾号为：", containerBaseInfo.ContainerName)
                    Dim endNum As String = String.Empty
                    For i As Integer = 1 To param.Qty
                        endNum = i.ToString("D3")
                        containerBaseInfo.ContainerName = String.Format("{0}{1}", containerName, endNum)
                        containerBaseInfo.Qty = 1
                        containerBaseInfo.QualificationNum = endNum
                        containerBaseInfo.BeginStep = dtWorkflowStep.Rows(0)("WORKFLOWSTEPNAME").ToString() '开始工序
                        AddContainerAttribute(containerBaseInfo, param.AutoType) '添加属性
                        result = CreateContainerInfo(containerBaseInfo, m_UserInfo) '开卡
                        If Not result.Result Then
                            message = If(i > 1, message.TrimEnd("，") + String.Format("开卡成功。尾号：{0}开卡失败并结束，原因：{1}", endNum, result.Message), result.Message)
                            result.Message = message
                            Exit For
                        End If
                        message += String.Format("{0}，", endNum)
                        '创建分卡批次
                        If drRule("iscutcontainer").ToString = "1" Then
                            Dim cutContainerName = containerBaseInfo.ContainerName '记下单卡的批次名
                            For cq = 1 To cutQty
                                containerBaseInfo.ContainerName = String.Format("{0}-{1}", cutContainerName, cq)
                                containerBaseInfo.Qty = 1
                                containerBaseInfo.QualificationNum = String.Format("{0}-{1}", endNum, cq)
                                containerBaseInfo.BeginStep = cutStepName '开始工序设置为分卡工序
                                AddContainerAttribute(containerBaseInfo, param.AutoType) '添加属性
                                result = CreateContainerInfo(containerBaseInfo, m_UserInfo) '开卡
                                If Not result.Result Then
                                    message = String.Format("{0}开卡成功。尾号：{1}下的分卡{2}开卡失败并结束，原因：{3}", message, endNum, containerBaseInfo.QualificationNum, result.Message)
                                    result.Message = message
                                    Exit For
                                End If
                            Next
                            '如果分卡出错，则直接结束
                            If Not result.Result Then
                                Exit For
                            End If
                        End If
                    Next
                Case "2"
                    AddContainerAttribute(containerBaseInfo, param.AutoType) '添加属性
                    result = CreateContainerInfo(containerBaseInfo, m_UserInfo) '开卡
                Case Else
                    result.Result = False
                    result.Message = "批次类型不明确"
            End Select

            If result.Result Then '如果开卡成功
                Dim dic As New Dictionary(Of String, Object)
                dic.Add("isselfmfg", drRule("isselfmfg").ToString())
                dic.Add("togetherflag", containerBaseInfo.TogetherFlag)
                dic.Add("fullname", m_UserInfo.FullName)
                dic.Add("employeeid", m_UserInfo.EmployeeID)
                sendToWms.SaveMaterialApplyJson(dic) '保存领料申请json到数据库，推送给WMS
                DeleAutoStartErrorInfo(param.MfgOrderID) '则删除该订单的历史开卡错误日志
            End If

        Catch ex As Exception
            result.Result = False
            result.Message = "开卡失败，原因：" & ex.Message
        End Try

        Return result
    End Function

    ''创建分卡批次
    'Private Function CreateSingleContainerByCut(ByVal containerBaseInfo As ContainerStartInfo, ByVal cutQty As Integer, ByVal cutStepName As String) As uMESProcessResult
    '    Dim result As New uMESProcessResult
    '    Dim cutContainerName = containerBaseInfo.ContainerName '记下单卡的批次名
    '    Dim endNum = containerBaseInfo.QualificationNum '记下单卡的尾号
    '    For cq = 1 To cutQty
    '        containerBaseInfo.ContainerName = String.Format("{0}-{1}", cutContainerName, cq)
    '        containerBaseInfo.Qty = 1
    '        containerBaseInfo.QualificationNum = String.Format("{0}-{1}", endNum, cq)
    '        AddContainerAttribute(containerBaseInfo, param.AutoType) '添加属性
    '        result = CreateContainerInfo(containerBaseInfo, m_UserInfo) '开卡
    '        If Not result.Result Then
    '            message = If(i > 1, message.TrimEnd("，") + String.Format("开卡成功。尾号：{0}开卡失败并结束，原因：{1}", endNum, result.Message), result.Message)
    '            result.Message = message
    '            Exit For
    '        End If
    '    Next

    'End Function

    ''' <summary>
    ''' 获取批次名
    ''' </summary>
    ''' <param name="productName"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function GetContainerName(ByVal productName As String) As String
        Dim year As String = DateTime.Now.Year.ToString().Substring(2, 2)
        Dim strPrefix As String = productName & "/" & year
        Dim childMaxIndex As Integer = commonBusiness.GetNewChildContainerNextIndex(strPrefix, 2) + 1
        Return strPrefix + String.Format("{0:D2}", childMaxIndex)
    End Function

    ''' <summary>
    ''' 获取开卡规则
    ''' </summary>
    ''' <param name="productName"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function GetContainerStartRuleInfo(ByVal productName As String) As DataTable
        Dim strSql = String.Format(<string>SELECT pb.productname,p.description,p.productrevision,wb1.workflowname,w.workflowrevision,ca.iscutcontainer,ca.cutqty,ca.cutstartstep,
                        ca.technologyempid,ca.status,ca.containerautostartruleid,wb1.workflowname ||':' || w.workflowrevision workflowinfo,w.workflowid,
                        ca.workcenterid,wc.workcentername,e.fullname technologyempName,e.employeename technologyNum,e1.fullname createname,ca.isselfmfg,ca.containertype,ca.createdate,
                        DECODE(ca.isselfmfg,0,'是','否') isselfmfgname,DECODE(ca.containertype,2,'批量加工',3,'批量带子序号',7,'单件单卡','') containertypename,
                        DECODE(ca.iscutcontainer,1,'是','否') iscutcontainername
                        FROM containerAutoStartRule ca
                        LEFT JOIN productbase pb ON pb.productname = ca.productname
                        LEFT JOIN product p ON p.productid = pb.revofrcdid
                        LEFT JOIN Workflowbase wb ON wb.workflowbaseid = p.workflowbaseid
                        LEFT JOIN Workflow w ON w.workflowid = NVL(wb.revofrcdid,p.workflowid)
                        LEFT JOIN Workflowbase wb1 ON wb1.workflowbaseid = w.workflowbaseid
                        LEFT JOIN Workcenter wc ON wc.workcenterid = ca.workcenterid
                        LEFT JOIN employee e ON e.employeeid = ca.technologyempid
                        LEFT JOIN employee e1 ON e1.employeeid = ca.createemployeeid
                        WHERE ca.productname = '{0}' AND ca.status = 1 </string>.Value, productName)

        Return DatabaseHelper.Query_ReturnDatTable(strSql)
    End Function

    ''' <summary>
    ''' 验证数据
    ''' </summary>
    ''' <param name="param"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function ValidAutoStartData(ByVal param As AutoStartContainerParam) As Tuple(Of Boolean, String)
        If String.IsNullOrWhiteSpace(param.MfgOrderName) Then
            Return New Tuple(Of Boolean, String)(False, "订单为空")
        End If

        If String.IsNullOrWhiteSpace(param.ProductName) Then
            Return New Tuple(Of Boolean, String)(False, "件号为空")
        End If

        If param.Qty Is Nothing Then
            Return New Tuple(Of Boolean, String)(False, "订单数为空")
        End If

        If param.PlannedStartDate Is Nothing Then
            Return New Tuple(Of Boolean, String)(False, "订单开始日期为空")
        End If

        If param.PlannedCompletionDate Is Nothing Then
            Return New Tuple(Of Boolean, String)(False, "订单结束日期为空")
        End If

        'If String.IsNullOrWhiteSpace(param.UomName) Then
        '    Return New Tuple(Of Boolean, String)(False, "订单计量单位为空")
        'End If

        If String.IsNullOrWhiteSpace(param.ProductFamilyName) Then
            param.ProductFamilyName = "-"
        End If

        Dim sql As String = String.Format("SELECT 1 FROM container c WHERE c.mfgorderid = '{0}' AND c.status != 0", param.MfgOrderID)

        If DatabaseHelper.GetSingle(sql) IsNot Nothing Then
            Return New Tuple(Of Boolean, String)(False, "订单存在已开卡数据")
        End If

        Return New Tuple(Of Boolean, String)(True, "")
    End Function

    ''' <summary>
    ''' 开卡
    ''' </summary>
    ''' <param name="containerBaseInfo"></param>
    ''' <param name="m_UserInfo"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function CreateContainerInfo(ByVal containerBaseInfo As ContainerStartInfo, ByVal m_UserInfo As CurrentUserInfo) As uMESProcessResult
        Dim result As uMESProcessResult = New uMESProcessResult() With {
            .Result = True,
            .Message = "开卡成功"
        }
        Dim serverInfo As ServerHostInfo = New ServerHostInfo()
        serverInfo.UserName = m_UserInfo.APIUserName
        serverInfo.Password = m_UserInfo.APIPassword
        containerBaseInfo.ServerHostInfo = serverInfo
        Dim tempResult As Camstar.WebClient.WebServicesProxy.InSiteWebServices.ResultStatus = containerBusiness.StartContainer(containerBaseInfo)

        If tempResult.IsError Then
            result.Result = False
            result.Message = String.Format("开卡失败，原因：{0}", tempResult.Message)
        End If

        Return result
    End Function

    ''' <summary>
    ''' 填充批次的机型
    ''' </summary>
    ''' <param name="containerBaseInfo"></param>
    ''' <remarks></remarks>
    Private Sub FillContainerProductFamily(ByRef containerBaseInfo As ContainerStartInfo, ByVal orderProductFamily As String)
        If orderProductFamily.Contains(",") Then '如果订单的机型包含逗号，则是多机型，需要分割并重组
            Dim strPF = orderProductFamily.Split(",")
            Dim batch = String.Empty
            Dim pfList = New Dictionary(Of Integer, String)
            For i = 0 To strPF.Length
                batch += String.Format("{0} ", strPF(i))
                pfList.Add(i + 1, strPF(i))
            Next
            containerBaseInfo.MfgBatch = String.Format("型别：{0}|", batch)
            containerBaseInfo.ProductFamilyList = pfList
        Else
            containerBaseInfo.MfgBatch = String.Format("型别：{0} |", orderProductFamily)
            containerBaseInfo.ProductFamilyList = New Dictionary(Of Integer, String) From {
                {1, orderProductFamily}
            }
        End If
    End Sub

    ''' <summary>
    ''' 填充批次默认信息
    ''' </summary>
    ''' <param name="containerBaseInfo"></param>
    ''' <param name="factoryId"></param>
    ''' <remarks></remarks>
    Private Sub FillContainerDefaultInfo(ByRef containerBaseInfo As ContainerStartInfo, ByVal factoryId As String)
        Dim levelAttributes As DataTable = commonBusiness.GetFatoryAttributes(factoryId)
        Dim datarows As DataRow() = levelAttributes.[Select]("USERATTRIBUTENAME='默认所有者'")
        Dim strOwner As String = ""

        If datarows.Length > 0 Then
            strOwner = datarows(0)("ATTRIBUTEVALUE").ToString()
        End If

        datarows = levelAttributes.[Select]("USERATTRIBUTENAME='默认层级'")
        Dim strLevel As String = ""

        If datarows.Length > 0 Then
            strLevel = datarows(0)("ATTRIBUTEVALUE").ToString()
        End If

        Dim strStart As String = ""

        If String.IsNullOrWhiteSpace(containerBaseInfo.MfgOrder.ToString()) Then
            datarows = levelAttributes.[Select]("USERATTRIBUTENAME='无订单开始原因'")
        Else
            datarows = levelAttributes.[Select]("USERATTRIBUTENAME='订单开始原因'")
        End If

        If datarows.Length > 0 Then
            strStart = datarows(0)("ATTRIBUTEVALUE").ToString()
        End If

        containerBaseInfo.StartReason = strStart
        containerBaseInfo.Level = strLevel
        containerBaseInfo.Owner = strOwner

        If containerBaseInfo.IsSelfMfg Then
            datarows = levelAttributes.[Select]("USERATTRIBUTENAME='自投料流程'")
        Else
            datarows = levelAttributes.[Select]("USERATTRIBUTENAME='领料流程'")
        End If

        If datarows.Length > 0 Then
            Dim strWorkflows As String() = datarows(0)("ATTRIBUTEVALUE").ToString().Split("："c)
            containerBaseInfo.WorkflowName = strWorkflows.First()
            containerBaseInfo.WorkflowRevision = strWorkflows.Last()
            containerBaseInfo.WorkflowuseROR = False
        End If
    End Sub
    ''' <summary>
    ''' 添加属性
    ''' </summary>
    ''' <param name="containerBase"></param>
    ''' <param name="type"></param>
    ''' <remarks></remarks>
    Private Sub AddContainerAttribute(ByRef containerBase As ContainerStartInfo, ByVal type As String)
        Dim userattributedt As DataTable = New DataTable()
        userattributedt.Columns.Add("Name")
        userattributedt.Columns.Add("Value")
        Dim dr As DataRow = userattributedt.NewRow()
        dr("Name") = "CheckTechnique"
        dr("Value") = containerBase.CheckTechnique
        userattributedt.Rows.Add(dr)
        dr = userattributedt.NewRow()
        dr("Name") = "BeginStep"
        dr("Value") = containerBase.BeginStep
        userattributedt.Rows.Add(dr)
        dr = userattributedt.NewRow()
        dr("Name") = "自动开卡"
        dr("Value") = type
        userattributedt.Rows.Add(dr)

        If containerBase.MonthPlan IsNot Nothing AndAlso Not String.IsNullOrWhiteSpace(containerBase.MonthPlan.ToString()) Then
            dr = userattributedt.NewRow()
            dr("Name") = "monthPlanName"
            dr("Value") = containerBase.MonthPlan
            userattributedt.Rows.Add(dr)
        End If

        Dim dtSameWorkflowVerifiedContainer As DataTable = containerBusiness.GetSameWorkflowVerifiedContainer(containerBase.MfgWorkflowName.ToString(), containerBase.MfgWorkflowRevision.ToString())

        If dtSameWorkflowVerifiedContainer.Rows.Count > 0 Then

            If containerBase.IsSelfMfg Then
                containerBase.WorkflowName = containerBase.MfgWorkflowName
                containerBase.WorkflowRevision = containerBase.MfgWorkflowRevision
            Else
                containerBase.WorkflowStep = "到料确认"
            End If

            dr = userattributedt.NewRow()
            dr("Name") = "工艺校对"
            dr("Value") = dtSameWorkflowVerifiedContainer.Rows(0)("techniquedate").ToString() & "&" + dtSameWorkflowVerifiedContainer.Rows(0)("techniqueemployeeid").ToString()
            userattributedt.Rows.Add(dr)
        End If

        If Not containerBase.IsSelfMfg Then '如果是领料
            dr = userattributedt.NewRow()
            dr("Name") = "材料牌号"
            dr("Value") = ""
            userattributedt.Rows.Add(dr)
            dr = userattributedt.NewRow()
            dr("Name") = "实发数/顺序号"
            dr("Value") = ""
            userattributedt.Rows.Add(dr)
            dr = userattributedt.NewRow()
            dr("Name") = "熔炉号母"
            dr("Value") = ""
            userattributedt.Rows.Add(dr)
            dr = userattributedt.NewRow()
            dr("Name") = "检验编号"
            dr("Value") = ""
            userattributedt.Rows.Add(dr)
            dr = userattributedt.NewRow()
            dr("Name") = "库房保管"
            dr("Value") = ""
            userattributedt.Rows.Add(dr)
            dr = userattributedt.NewRow()
            dr("Name") = "器材检验"
            dr("Value") = ""
            userattributedt.Rows.Add(dr)
            dr = userattributedt.NewRow()
            dr("Name") = "代料牌号"
            dr("Value") = ""
            userattributedt.Rows.Add(dr)
            dr = userattributedt.NewRow()
            dr("Name") = "代料规格"
            dr("Value") = ""
            userattributedt.Rows.Add(dr)
            dr = userattributedt.NewRow()
            dr("Name") = "代料单号"
            dr("Value") = ""
            userattributedt.Rows.Add(dr)
            dr = userattributedt.NewRow()
            dr("Name") = "平行作业单号"
            dr("Value") = ""
            userattributedt.Rows.Add(dr)
            dr = userattributedt.NewRow()
            dr("Name") = "平行作业工序"
            dr("Value") = ""
            userattributedt.Rows.Add(dr)
            dr = userattributedt.NewRow()
            dr("Name") = "顾客代表"
            dr("Value") = ""
            userattributedt.Rows.Add(dr)
            dr = userattributedt.NewRow()
            dr("Name") = "不合格审理单号"
            dr("Value") = ""
            userattributedt.Rows.Add(dr)
        End If

        userattributedt.AcceptChanges()
        containerBase.AttributeList = userattributedt
    End Sub

    ''' <summary>
    ''' 创建自动开卡错误日志 add by zhangrj 20231212
    ''' </summary>
    ''' <param name="para"></param>
    ''' <remarks></remarks>
    Public Sub CreateAutoStartErrorInfo(ByVal para As Dictionary(Of String, String))
        Dim strSql = <string> INSERT INTO AutoStartContainerErrorInfo(ErrorInfoID,MfgOrderID,MfgorderName,ProductName,CreateEmpID,CreateDate,Notes,FactoryID)
                              VALUES('{0}','{1}','{2}','{3}','{4}',to_date('{5}','yyyy-mm-dd hh24:mi:ss'),'{6}','{7}') </string>.Value
        strSql = String.Format(strSql, Guid.NewGuid.ToString(), para("MfgOrderID"), para("MfgOrderName"), para("ProductName"), para("CreateEmpID"), DateTime.Now.ToString(), para("Notes").Replace("'", ""), para("FactoryID"))
        DatabaseHelper.ExecuteSql(strSql)
    End Sub

    ''' <summary>
    ''' 删除自动开卡报错记录信息 add by zhangrj 20231212
    ''' </summary>
    ''' <param name="mfgOrderID"></param>
    ''' <remarks></remarks>
    Public Sub DeleAutoStartErrorInfo(ByVal mfgOrderID As String)
        Dim strSql = "DELETE AutoStartContainerErrorInfo r WHERE r.MfgOrderID = '{0}'"
        strSql = String.Format(strSql, mfgOrderID)
        DatabaseHelper.ExecuteSql(strSql)
    End Sub

    ''' <summary>
    ''' 删除自动开卡报错记录信息 add by zhangrj 20231212
    ''' </summary>
    ''' <param name="mfgOrderName"></param>
    ''' <remarks></remarks>
    Public Sub DeleAutoStartErrorInfoByName(ByVal mfgOrderName As String)
        Dim strSql = "DELETE AutoStartContainerErrorInfo r WHERE r.mfgOrderName = '{0}'"
        strSql = String.Format(strSql, mfgOrderName)
        DatabaseHelper.ExecuteSql(strSql)
    End Sub

    ''' <summary>
    ''' 获取自动开卡错误列表 add by zhangrj 20231213
    ''' </summary>
    ''' <param name="para"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function GetAutoStartContainerErrorList(ByVal para As Dictionary(Of String, String)) As uMESProcessResult
        Dim strSql As New StringBuilder
        strSql.AppendFormat(<string>
                          SELECT ac.mfgordername,ac.productname,ac.notes,ac.createdate,e.fullname,f.factoryname,wct.workcentername,te.teamname
                        FROM AutoStartContainerErrorInfo ac
                        LEFT JOIN employee e ON e.employeeid = ac.createempid
                        LEFT JOIN productteaminfo pti ON pti.productname = ac.productname AND pti.isuse = 0
                        LEFT JOIN team te ON te.teamid = pti.teamid
                        LEFT JOIN workcenter wct ON wct.workcenterid = te.workcenterid
                        LEFT JOIN factory f ON f.factoryid = wct.factoryid
                        WHERE ac.factoryid = '{0}'
                     </string>.Value, para("FactoryID"))
        If para.ContainsKey("mfgOrderName") Then
            If Not String.IsNullOrWhiteSpace(para("mfgOrderName")) Then
                strSql.AppendFormat(" AND ac.mfgordername = '{0}'", para("mfgOrderName"))
            End If
        End If
        If para.ContainsKey("productName") Then
            If Not String.IsNullOrWhiteSpace(para("productName")) Then
                strSql.AppendFormat(" AND ac.productname like '%{0}%'", para("productName"))
            End If
        End If

        If para.ContainsKey("ddlFactory") Then
            If Not String.IsNullOrWhiteSpace(para("ddlFactory")) Then
                strSql.AppendFormat(" AND f.factoryid = '{0}'", para("ddlFactory"))
            End If
        End If

        If para.ContainsKey("ddlWorkcenter") Then
            If Not String.IsNullOrWhiteSpace(para("ddlWorkcenter")) Then
                strSql.AppendFormat(" AND wct.workcenterid = '{0}'", para("ddlWorkcenter"))
            End If
        End If

        If para.ContainsKey("ddlTeam") Then
            If Not String.IsNullOrWhiteSpace(para("ddlTeam")) Then
                strSql.AppendFormat(" AND te.teamid = '{0}'", para("ddlTeam"))
            End If
        End If

        Dim paraPage As New uMESPagingDataDTO
        paraPage.CurrentPageIndex = Convert.ToInt32(para("pageIndex"))
        paraPage.PageSize = Convert.ToInt32(para("pageSize"))
        paraPage.strSQL = strSql.ToString()
        Return DatabaseHelper.RunProcedureForPage(paraPage)
    End Function

End Class
